﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Variedades;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;
using Cesave.Domain.Core.Entities;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Variedades
{
    /// <summary>
    /// Manejo de variedades.
    /// </summary>
	public partial class VariedadesViewModel
    {
        #region Private properties

        /// <summary>
        /// Lista de variedades.
        /// </summary>
        private List<Variedad> _variedades;

        /// <summary>
        /// Variedad seleccionada.
        /// </summary>
        private Variedad _variedad;

        #endregion

        #region Public properties

        /// <summary>
        /// Lista de variedades.
        /// </summary>
        public List<Variedad> Variedades
        {
            get
            {
                return _variedades;
            }
            private set
            {
                _variedades = value;
                if (_variedades != null)
                    RaisePropertyChanged("Variedades");
            }
        }

        /// <summary>
        /// Variedad seleccionada.
        /// </summary>
        public Variedad Variedad
        {
            get
            {
                return _variedad;
            }
            private set
            {
                _variedad = value;
                if (_variedad != null)
                    RaisePropertyChanged("Variedad");
            }
        }

		public bool IsVariedadReady
		{
			get
			{
				return Variedad != null;
			}
		}

        #endregion

        #region Private properties

		private void LoadVariedades()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IVariedadService service = IoCFactory.Resolve<IVariedadService>();
					e.Result = service.FindVariedadesByCultivo(Cultivo.CultivoGuid);
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Variedades = e.Result as List<Variedad>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

        #endregion

		#region Event methods

		private void AddNewVariedad(object sender, EventArgs e)
		{
			_view.variedadesBindingSource.AddingNew += AddingNewVariedad;
			_view.variedadesBindingSource.AddNew();
		}

		private void AddingNewVariedad(object sender, AddingNewEventArgs e)
		{
			Variedad = new Variedad
			{
				CultivoGuid = Cultivo.CultivoGuid,
				CultivoId = Cultivo.CultivoId,
				GrupoGuid = Guid.Empty,
				GrupoId = 0,
				Nombre = string.Empty,
				Status = true,
				VariedadGuid = Guid.NewGuid(),
				VariedadId = 0,
			};
			Variedad.MarkAsAdded();
			e.NewObject = Variedad;
			FocusDefaultControl();
		}

		private void SaveVariedades(object s, EventArgs args)
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IVariedadService service = IoCFactory.Resolve<IVariedadService>();
					Variedades.ForEach(variedad =>
					{
						if (variedad.ChangeTracker.State == ObjectState.Added)
							service.AddVariedad(variedad);
						else
							service.ChangeVariedad(variedad);
						variedad.AcceptChanges();
					});
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						LoadVariedades();
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		/// <summary>
		/// Identifica la variedad seleccionada.
		/// </summary>
		private void SetCurrentVariedad(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null && bindingSource.Current != null)
				Variedad = bindingSource.Current as Variedad;
		}

		private void OnVariedadesPropertyChanged()
		{
			_view.variedadesBindingSource.DataSource = Variedades;
			_view.variedadesBindingSource.CurrentChanged += SetCurrentVariedad;
			SetCurrentVariedad(_view.variedadesBindingSource, new EventArgs());
		}

		private void OnVariedadPropertyChanged()
		{
		}

		#endregion

	}
}
